<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        left: 0;
        top: 0;
      }
      .box2 {
        width: 100px;
        height: 100px;
        background: gray;
        position: absolute;
        top: 200px;
        left: 50px;
      }
    </style>
  </head>
  <body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
      var box1Ele = document.querySelector(".box1");
      var box2Ele = document.querySelector(".box2");
      box2Ele.onmousedown = function (e) {
        var x = e.clientX - this.offsetLeft;
        var y = e.clientY - this.offsetTop;
        this.onmousemove = function (e) {
          var xx = e.clientX;
          var yy = e.clientY;
          this.style.left = xx - x + "px";
          this.style.top = yy - y + "px";
        };
        this.onmouseup = function () {
          this.onmousemove = "";
        };
      };
      let speed = 5;
      var flag = true;
      setInterval(function () {
        var leftNum = parseInt(getComputedStyle(box1Ele, null)["left"]);
        var dis = window.innerWidth - box1Ele.offsetWidth;
        if (leftNum >= dis) {
          speed *= -1;
        }
        if (leftNum < 0) {
          speed *= -1;
        }
        var res = leftNum + speed;
        box1Ele.style.left = res + "px";
        if (
          Math.abs(box1Ele.offsetLeft - box2Ele.offsetLeft) <
            box1Ele.offsetWidth &&
          Math.abs(box1Ele.offsetTop - box2Ele.offsetTop) < box1Ele.offsetHeight
        ) {
          console.log("横轴上碰撞了");
          if (flag) {
            speed *= -1;
            flag = false;
            setTimeout(function () {
              flag = true;
            }, 500);
          }
        }
      }, 20);
    </script>
  </body>
</html>
